import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easylogger/flutter_logger.dart';

import '../../../../http/http_service.dart';
import '../../../../models/category_model.dart';
import '../../../../utils/user_info_utils.dart';

class FoodManagementLogic extends GetxController {
  // 分类列表
  final categories = <Category>[].obs;

  // 菜品列表
  final foods = <Food>[].obs;

  // 加载状态
  final isLoading = false.obs;

  // 编辑状态
  final isEditing = false.obs;

  // 当前编辑的菜品
  final editingFood = Rxn<Food>();

  // 表单控制器
  final nameController = TextEditingController();
  final priceController = TextEditingController();
  final imageController = TextEditingController();
  final descriptionController = TextEditingController();
  final selectedCategoryId = RxnInt();

  // HTTP服务
  final httpService = HttpService();

  @override
  void onInit() {
    super.onInit();
    loadData();
  }

  @override
  void onClose() {
    nameController.dispose();
    priceController.dispose();
    imageController.dispose();
    descriptionController.dispose();
    super.onClose();
  }

  // 加载数据
  Future<void> loadData() async {
    if (isLoading.value) return;

    isLoading.value = true;

    try {
      final response = await httpService.get('/menu');
      final responseData = response.data;

      // 解析分类数据
      final List<dynamic> categoriesData = responseData['categories'];
      categories.clear();
      categories.addAll(categoriesData.map((data) => Category(
        id: data['id'],
        name: data['name'],
      )));

      // 解析菜品数据
      final List<dynamic> foodsData = responseData['foods'];
      foods.clear();
      foods.addAll(foodsData.map((data) => Food(
        id: data['id'],
        categoryId: data['categoryId'],
        name: data['name'],
        price: double.parse(data['price'].toString()),
        image: data['image'],
        description: data['description'] ?? '',
      )));

      Logger.i('菜单加载成功: ${categories.length}个分类, ${foods.length}个菜品');
    } catch (e) {
      Logger.e('菜单加载失败: $e');
      Get.snackbar(
        '加载失败',
        '菜单数据加载失败，请检查网络连接',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
        duration: Duration(seconds: 2),
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 添加菜品
  void addFood() {
    isEditing.value = true;
    editingFood.value = null;
    
    // 清空表单
    nameController.clear();
    priceController.clear();
    imageController.clear();
    descriptionController.clear();
    selectedCategoryId.value = categories.isNotEmpty ? categories[0].id : null;
  }

  // 编辑菜品
  void editFood(Food food) {
    isEditing.value = true;
    editingFood.value = food;
    
    // 填充表单
    nameController.text = food.name;
    priceController.text = food.price.toString();
    imageController.text = food.image;
    descriptionController.text = food.description;
    selectedCategoryId.value = food.categoryId;
  }

  // 取消编辑
  void cancelEdit() {
    isEditing.value = false;
    editingFood.value = null;
  }

  // 保存菜品
  Future<void> saveFood() async {
    if (nameController.text.isEmpty || 
        priceController.text.isEmpty || 
        imageController.text.isEmpty || 
        selectedCategoryId.value == null) {
      Get.snackbar(
        '错误',
        '请填写所有必填字段',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
      return;
    }

    double? price = double.tryParse(priceController.text);
    if (price == null || price <= 0) {
      Get.snackbar(
        '错误',
        '价格必须是有效的正数',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
      return;
    }

    isLoading.value = true;

    try {
      // 获取用户ID
      var loginModel = DataUtils().getLoginModel();
      var userId = loginModel.id;

      if (userId == null) {
        throw Exception('未获取到用户ID');
      }

      final foodData = {
        'categoryId': selectedCategoryId.value,
        'name': nameController.text,
        'price': price,
        'image': imageController.text,
        'description': descriptionController.text,
      };

      if (editingFood.value == null) {
        // 创建新菜品
        await httpService.post('/foods', data: foodData, queryParameters: {'userId': userId});
        Get.snackbar(
          '成功',
          '菜品添加成功',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
        );
      } else {
        // 更新现有菜品
        await httpService.put('/foods/${editingFood.value!.id}', 
          data: foodData, 
          queryParameters: {'userId': userId}
        );
        Get.snackbar(
          '成功',
          '菜品更新成功',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
        );
      }

      // 重新加载数据
      await loadData();
      
      // 关闭编辑模式
      isEditing.value = false;
      editingFood.value = null;
    } catch (e) {
      Logger.e('保存菜品失败: $e');
      Get.snackbar(
        '错误',
        '保存菜品失败: ${e.toString()}',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 删除菜品
  Future<void> deleteFood(Food food) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除菜品 "${food.name}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    isLoading.value = true;

    try {
      // 获取用户ID
      var loginModel = DataUtils().getLoginModel();
      var userId = loginModel.id;

      if (userId == null) {
        throw Exception('未获取到用户ID');
      }

      await httpService.delete('/foods/${food.id}', queryParameters: {'userId': userId});
      
      Get.snackbar(
        '成功',
        '菜品删除成功',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green.withOpacity(0.8),
        colorText: Colors.white,
      );

      // 重新加载数据
      await loadData();
    } catch (e) {
      Logger.e('删除菜品失败: $e');
      Get.snackbar(
        '错误',
        '删除菜品失败: ${e.toString()}',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
    } finally {
      isLoading.value = false;
    }
  }
}
